// 本地鉴权策略

import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly authService: AuthService) {
    super();
  }

  /**
   * 验证用户是否存在或用户名密码是否正确
   * 验证成功：会在request中增加一个user对象（req.user），即方法的返回值
   * 验证失败：抛出UnauthorizedException
   */
  async validate(username: string, password: string): Promise<any> {    
    const user = await this.authService.validateUser(username, password);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}